package com.chenwc.aliyunoss;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 进度条用于指示上传或下载文件的进度。
 *
 * @author chenwc
 */
public class PutObjectProgressListener implements ProgressListener {

    private static final Logger log = LoggerFactory.getLogger(PutObjectProgressListener.class);

    private long bytesWritten = 0;
    private long totalBytes = -1;
    private boolean succeed = false;

    public boolean isSucceed() {
        return succeed;
    }

    // 使用进度条需要您重写回调方法，以下仅为参考示例。
    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                log.info("开始上传......");
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                log.info(this.totalBytes + "字节将被上传到 OSS");
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                if (this.totalBytes != -1) {
                    int percent = (int) (this.bytesWritten * 100.0 / this.totalBytes);
                    log.info(bytes + " 字节已写入，上载进度：" + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
                } else {
                    log.info(bytes + " 字节已写入，上载比率：未知: " + "(" + this.bytesWritten + "/…)");
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                log.info("上传成功，共传输" + this.bytesWritten + "个字节");
                break;
            case TRANSFER_FAILED_EVENT:
                log.info("上传失败，" + this.bytesWritten + "字节已传输");
                break;
            default:
                break;
        }
    }
}
